﻿using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ClassStyle
{
    public class FileHelper2025
    {
    

        #region 全局变量
        [DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
        [DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string section, string key, string def, System.Text.StringBuilder retVal, int size, string filePath);
        [DllImport("kernel32.dll")]
        private static extern int GetPrivateProfileSection(string lpAppName, byte[] lpszReturnBuffer, int nSize, string lpFileName);

        #endregion


        #region ini文件操作
        public static string Get_ini_data(string title, string name, string ini_path)
        {
            StringBuilder sb = new StringBuilder(255);
            GetPrivateProfileString(title, name, "", sb, 255, ini_path);
            return sb.ToString();
        }
        public static void Set_ini_data(string title, string name, string value, string ini_path)
        {
            WritePrivateProfileString(title, name, value, ini_path);
        }
        //修改标题
        public static void UpdateSection(string iniFilePath, string oldSection, string newSection)
        {
            // 创建 StringBuilder 来保存旧节中的数据  
            System.Text.StringBuilder sb = new System.Text.StringBuilder(1024);

            // 遍历旧节中的所有键并将其写入新节  
            int size = GetPrivateProfileString(oldSection, newSection, null, sb, sb.Capacity, iniFilePath);

            // 获取所有键值对  
            string[] keys = sb.ToString().Split(new[] { '\0' }, StringSplitOptions.RemoveEmptyEntries);
            foreach (string key in keys)
            {
                // 获取每个键的值  
                StringBuilder value = new StringBuilder(1024);
                GetPrivateProfileString(oldSection, key, null, value, value.Capacity, iniFilePath);

                // 将键值对写入新节  
                WritePrivateProfileString(newSection, key, value.ToString(), iniFilePath);
            }

            // 删除旧节  
            WritePrivateProfileString(oldSection, null, null, iniFilePath);

            Console.WriteLine($"成功将节 '{oldSection}' 修改为 '{newSection}'");
        }
        /// <summary>
        /// 只修改标题
        /// </summary>
        /// <param name="iniFilePath"></param>
        /// <param name="oldSection"></param>
        /// <param name="newSection"></param>
        public static void Update_ini_Title(string iniFilePath, string oldSection, string newSection)
        {
            string path = iniFilePath;
            string path2 = System.AppDomain.CurrentDomain.BaseDirectory + "tmp.ini";
            string old = oldSection;
            string newV = newSection;
            using (StreamReader sr = new StreamReader(new FileStream(path, FileMode.OpenOrCreate), Encoding.Default))
            {
                using (StreamWriter sw = new StreamWriter(new FileStream(path2, FileMode.OpenOrCreate, FileAccess.Write), Encoding.Default))
                {
                    string line = string.Empty;
                    while ((line = sr.ReadLine()) != null)
                    {
                        if (line.Contains("[" + old + "]"))//我们要去修改的标题
                        {
                            sw.WriteLine("[" + newV + "]");
                            continue;
                        }
                        sw.WriteLine(line);
                    }
                }
            }
            File.Delete(path);
            File.Copy(path2, path);
            File.Delete(path2);
        }
        //删除标题
        public static bool Delete_ini_Titles(String title, String ini_path)
        {
            long result = WritePrivateProfileString(title, null, null, ini_path);
            if (result != 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// //删除指定标题下 指定的键(将值设置为空)
        /// </summary>
        /// <param name="path"></param>
        /// <param name="_title"></param>
        /// <param name="del_key"></param>
        public static void RemoveKey(string path, string _title, string del_key)
        {

            //string otherPath = path;
            ////获取所有的标题
            //List<string> titles = GetIniAllTitles(path);
            //foreach (var titie in titles)
            //{
            //    //根据标题获取每一个标题下的所有的键值对
            //    Dictionary<string, string> kvs = GetKeyValuePairs(path, titie);
            //    foreach (KeyValuePair<string, string> item in kvs)
            //    {
            //        string key = item.Key;
            //        string value = item.Value;

            //    }
            //}
            //值为空，我们就直接删除当前行
            Set_ini_data(_title, del_key, null, path + "\\clas.ini");

        }

        //ini文件  获取所有的标题
        public static List<string> GetIniAllTitles(string path) {
            List<string> titles = new List<string>();
            if (File.Exists(path))
            {
                string[] lines = File.ReadAllLines(path,Encoding.Default);
                string[] sections = Array.FindAll(lines, line => line.StartsWith("[") && line.EndsWith("]"));

                foreach (string section in sections)
                {
                    string title = section.Substring(1, section.Length - 2);
                    
                    titles.Add(title);
                }
                return titles;
            }
            else
            {
                Console.WriteLine("INI file does not exist.");
            }
            return null;
        }

        //ini文件获取文件下 对应标题的所有的键


        public static Dictionary<string, string> GetKeyValuePairs(string path, string title)
        {
            if (File.Exists(path))
            {
                Dictionary<string, string> sectionValues = new Dictionary<string, string>();

                string[] lines = File.ReadAllLines(path, Encoding.Default);
                int sectionStartIndex = Array.FindIndex(lines, line => line.Trim() == "[" + title + "]");

                if (sectionStartIndex != -1)
                {
                    int sectionEndIndex = Array.FindIndex(lines, sectionStartIndex + 1, line => line.Trim().StartsWith("["));
                    if (sectionEndIndex == -1)
                    {
                        sectionEndIndex = lines.Length;
                    }

                    for (int i = sectionStartIndex + 1; i < sectionEndIndex; i++)
                    {
                        string line = lines[i].Trim();
                        if (!string.IsNullOrEmpty(line) && !line.StartsWith(";"))
                        {
                            string[] keyValue = line.Split('=');
                            if (keyValue.Length == 2)
                            {
                                string key = keyValue[0].Trim();
                                string value = keyValue[1].Trim();
                                sectionValues.Add(key, value);
                            }
                        }
                    }

                    //foreach (KeyValuePair<string, string> keyValue in sectionValues)
                    //{
                    //    Console.WriteLine($"Key: {keyValue.Key}, Value: {keyValue.Value}");
                    //}
                    return sectionValues;
                }
                else
                {
                    Console.WriteLine($"Section '{title}' not found.");
                }
            }
            else
            {
                Console.WriteLine("INI file does not exist.");
            }
            return null;
        }

        public static List<string> GetKeys(string path, string title)
        {
            if (File.Exists(path))
            {
                List<string> keys = new List<string>();

                string[] lines = File.ReadAllLines(path, Encoding.Default);
                int sectionStartIndex = Array.FindIndex(lines, line => line.Trim() == "[" + title + "]");

                if (sectionStartIndex != -1)
                {
                    int sectionEndIndex = Array.FindIndex(lines, sectionStartIndex + 1, line => line.Trim().StartsWith("["));
                    if (sectionEndIndex == -1)
                    {
                        sectionEndIndex = lines.Length;
                    }

                    for (int i = sectionStartIndex + 1; i < sectionEndIndex; i++)
                    {
                        string line = lines[i].Trim();
                        if (!string.IsNullOrEmpty(line) && !line.StartsWith(";"))
                        {
                            string[] keyValue = line.Split('=');
                            if (keyValue.Length == 2)
                            {
                                string key = keyValue[0].Trim();
                                keys.Add(key);
                            }
                        }
                    }

                    //foreach (KeyValuePair<string, string> keyValue in sectionValues)
                    //{
                    //    Console.WriteLine($"Key: {keyValue.Key}, Value: {keyValue.Value}");
                    //}
                    return keys;
                }
                else
                {
                    Console.WriteLine($"Section '{title}' not found.");
                }
            }
            else
            {
                Console.WriteLine("INI file does not exist.");
            }
            return null;
        }


        #endregion

        //将数据写入到txt文件去
        public static void Write2Txt(string path, List<string> list, FileMode mode = FileMode.Create) {
            using (FileStream fs = File.Open(path, mode)) {
                using (StreamWriter sw = new StreamWriter(fs)) {

                    list.ForEach(v => {
                        sw.Write(v);//s.o.pln
                        //wirte  writeLine换行
                    });
                }
            }
        }

        //将数据写入到txt文件去
        //一行一行的去读取
        public static List<string> Read4Txt(string path, FileMode mode = FileMode.OpenOrCreate)
        {
            List<string> list = new List<string>();
            using (FileStream fs = File.Open(path, mode))
            {
                using (StreamReader sw = new StreamReader(fs))
                {
                    string con = string.Empty;
                    while ((con = sw.ReadLine()) != null)
                    {
                        list.Add(con);
                    }
                }
            }
            return list;
        }

        //特定项目  我们要加入Form对象



        /// <summary>
        /// 日志处理
        /// </summary>
        /// <param name="value"></param>
        /// <param name="index"></param>
        /// <param name="RootPath"></param>
        /// <param name="Style"></param>
        public static void TxtLog(string value,Form1 form, int index=1, string RootPath = "", string Style = "程序日志") // 日志
        {

            // 选择在哪个日志里面显示
            switch (index)
            {
                case 1:                    
                    form.dataLog.AppendText(DateTime.Now.ToString("yyyy年MM月dd日 HH:mm;ss") + " " + value + "\r\n"); // 主窗口日志控件
                    //form.textBox2.SelectionStart = form.textBox2.Text.Length - 1;                   
                    break;

            }
            RootPath = System.Windows.Forms.Application.StartupPath;
            string currPath = RootPath + "/" + DateTime.Now.ToString("yyyy年MM月dd日");  //创建当天时间文件夹
            string subPath = currPath + "/";
            if (Directory.Exists(currPath) == false)
            {
                Directory.CreateDirectory(currPath);
            }
            if (Directory.Exists(subPath) == false)//如果不存在就创建file文件夹 
            {
                Directory.CreateDirectory(subPath);
            }
            try
            {
                FileStream fs = new FileStream(subPath + "\\" + DateTime.Now.ToString("yyyy年MM月dd日") + "日志文件.txt", FileMode.Append);
                StreamWriter wr = new StreamWriter(fs);
                wr.WriteLine(DateTime.Now.ToString() + " " + value);
                wr.Close();
            }
            catch (Exception) { }
        }

        /// <summary> 读取CSV表里面全部的内容
        /// </summary>
        public static List<string> Read_CSV(string FliePath)
        {
            string str2 = FliePath;
            //if (!Directory.Exists(str2))// 如果CSV文件不存在了，就需要提示
            if (!File.Exists(str2))
            {
                return null;
            }
            StreamReader reader = new StreamReader(str2, System.Text.Encoding.Default);
            string line = "";
            List<string> listStrArr = new List<string>();
            while ((line = reader.ReadLine()) != null)
            {
                listStrArr.Add(line);//将文件内容分割成数组
            }
            reader.Close();
            return listStrArr;
        }
        /// <summary>
        /// 通过第一列的那个数据去删除行
        /// </summary>
        /// <param name="FliePath"></param>
        /// <param name="key"></param>
        /// <returns>除了要删除的数据以外的其他数据  返回</returns>
        public static List<string> RemoveDataAtIndex(string FilePath,string key)
        {
            string str2 = FilePath;
            string tmp = Path.GetDirectoryName(FilePath) + "\\tmp.CSV";
            //1读取数据
            List<string> list = Read_CSV(FilePath);
            List<string> newList = new List<string>();
            newList.Add(list[0]);//增加标题
            //2分拣数据
            for(int i = 1 ; i < list.Count;i++)
            {
                //找到我们要的数据
                if (list[i].StartsWith(key + ","))
                {
                    continue;
                }
                //3写入数据到另外一个 为文件
                Write_CSV(list[i].Split(','), Path.GetDirectoryName(FilePath), "tmp", list[0].Split(','));
                //Write_CSV(list[i].Split(','), Path.GetDirectoryName(FilePath), "tmp");
                newList.Add(list[i]);
            }
            //将文件修改名字
            File.Delete(FilePath);
            File.Copy(tmp, FilePath);
            File.Delete(tmp);

            return newList;
        }

        /// <summary>
        /// 通过指定的下标去修改数据
        /// </summary>
        /// <param name="FliePath"></param>
        /// <param name="key"></param>
        /// <returns>数据以外的其他数据  返回</returns>
        public static List<string> UpdateDataAtIndex(string FilePath, string[] oldArr, string[] newArr)
        {
            string str2 = FilePath;
            string tmp = Path.GetDirectoryName(FilePath) + "\\tmp.CSV";
            //1读取数据
            List<string> list = Read_CSV(FilePath);
            List<string> newList = new List<string>();
            newList.Add(list[0]);//增加标题
            //2分拣数据
            for (int i = 1; i < list.Count; i++)
            {
                //找到我们要的数据
                if (list[i].StartsWith(oldArr[0] + ","))
                {
                    string dest = string.Empty;
                    for (int a = 0; a < newArr.Length; a++)
                    {
                        dest += newArr[a] + ",";
                    }
                    Write_CSV(dest.Substring(0,dest.Length-1).Split(','), Path.GetDirectoryName(FilePath), "tmp", list[1].Split(','));
                    continue;
                }
                //3写入数据到另外一个 为文件
                Write_CSV(list[i].Split(','), Path.GetDirectoryName(FilePath), "tmp", list[1].Split(','));
                //Write_CSV(list[i].Split(','), Path.GetDirectoryName(FilePath), "tmp");
               
            }
            //将文件修改名字
            File.Delete(FilePath);
            File.Copy(tmp, FilePath);
            File.Delete(tmp);

            return newList;
        }

        public static void Write_CSV(object[] content, string RootPath = "", string fileName = "", string[] TitleArray=null)// CSV表写入操作
        {
            StreamWriter writer = null;
            //string RootPath = System.Windows.Forms.Application.StartupPath;
            try
            {
                string str2 = RootPath + "\\" + (fileName == "" ? DateTime.Now.ToString("yyyy年MM月dd日") : fileName) + ".CSV";
                if (!File.Exists(str2))// 如果CSV文件不存在了，就需要重新创建一个CSV文件，并生成标题
                {
                    Write_CSV_Title(str2, TitleArray);
                }
                writer = new StreamWriter(new FileStream(str2, FileMode.Append, FileAccess.Write, FileShare.ReadWrite), System.Text.Encoding.Default);
                if (content==null)
                {
                    return;
                }
                // 向文件里面写入数据
                string str3 = "";
                int index = 0;
                try
                {
                    while (true)
                    {
                        if (index >= content.Length)
                        {
                            writer.WriteLine(str3);
                            writer.Close();
                            break;
                        }
                        if (index > 0)
                        {
                            str3 = str3 + ",";
                        }
                        str3 = str3 + content[index];
                        index++;
                    }
                }
                catch (Exception exception)
                {
                    throw new Exception("导出错误" + exception.Message);
                }
            }
            catch (System.IO.DirectoryNotFoundException ex)
            {
                //MessageBox.Show("CSV路径下的文件夹不存在，程序无法搜索到指定的路径！" + ex.Message);
            }
            catch (System.IO.IOException ex)
            {
                // MessageBox.Show("模组数据录入失败！\r\n\r\n原因：当天的CSV数据文件在外部被打开，请关闭！\r\n注意：Except文档不能被两名用户同时打开！", "危险错误提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly);
            }
        }

        private static void Write_CSV_Title(string fileName, object[] content) // 写入表头数据
        {
            StreamWriter writer = new StreamWriter(new FileStream(fileName, FileMode.Append, FileAccess.Write, FileShare.ReadWrite), System.Text.Encoding.Default);
            // 向文件里面写入数据
            string str3 = "";
            int index = 0;
            try
            {
                while (true)
                {
                    if (index >= content.Length)
                    {
                        writer.WriteLine(str3);
                        writer.Close();
                        break;
                    }
                    if (index > 0)
                    {
                        str3 = str3 + ",";
                    }
                    str3 = str3 + content[index];
                    index++;
                }
            }
            catch (Exception exception)
            {
                throw new Exception("导出错误" + exception.Message);
            }
        }
       
    }
}
